<script  lang="ts">
import {ImportRecordVO, Result} from "~/api/responseResult";
import { UploadFilled } from '@element-plus/icons-vue'
import { ElMessage } from "element-plus";

export default defineComponent({
  name: 'CustomUpload',
  components: {UploadFilled},
  props: {
    tablePid: {
      type: String,
      default: '',
    },
    uploadSuccess: {
      type: Function,
      default: () => {}
    }
  },
  setup(props) {
    const token = localStorage.getItem("token")
    const baseURL = (import.meta.env.VITE_BASE_URL as string)
    const uploadUrl = baseURL + "/upload/excel"
    const headers = {token: token}

    const state: {loading: boolean} = reactive({
      loading: false
    })

    const uploadSuccess = (response: Result<ImportRecordVO>) => {
      state.loading = false
      if (response.success) {
          props.uploadSuccess(response.data)
      } else {
        ElMessage.warning({
          message: response.message,
        })
      }
    }
    const beforeUpload = (file: { size: string | number; type: string; }) => {
      console.log("文件大小：" + file.size)
      console.log("文件格式：" + file.type)
      if (file.size > 200 * 1024 * 1024) {
        ElMessage.warning({
          message: '文件过大',
        })
        return false
      }
      const type = ".csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,.xlsx,.xls"
      if (type.indexOf(file.type) >= 0) {
        state.loading = true
      } else {
        ElMessage.warning({
          message: '文件格式不正确',
        })
        return false
      }
    }
    const onError = () => {
      ElMessage.warning({
        message: '上传失败',
      })
      state.loading = false;
    }
    return {
      ...toRefs(state),
      props,
      uploadUrl,
      headers,
      uploadSuccess,
      beforeUpload,
      onError
    }

  }
})






</script>

<template>
    <div style="text-align: center" v-loading="loading">
      <span style="color: rgb(0, 128, 0);">提示文本：导入后只会保留Excel中的数据及通过公式计算后的值，设置的文字颜色等样式、合并的单元格、以及计算公式本身都不会被保留</span>
      <el-upload
          style="margin-top: 5px"
          class="upload-demo"
          drag
          :show-file-list="false"
          :headers="headers"
          :action="uploadUrl"
          :data="{tablePid:tablePid}"
          :on-error="onError"
          :before-upload="beforeUpload"
          :on-success="uploadSuccess"
          accept=".csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,.xlsx,.xls"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          <div>点击选择文件或将文件拖拽到这里上传</div>
          <div>导入支持 200MB 以内的xls、xlsx、csv</div>
        </div>
      </el-upload>
    </div>
</template>

<style  lang="scss" scoped>
.upload-demo{
  ::v-deep .el-upload-dragger {
    width: 1000px;
    height: 400px;
  }
  ::v-deep .el-upload-dragger .el-icon--upload {
    margin: 100px 0 16px;
  }
}
</style>
